//
//  WeiboService.m
//  Study1
//
//  Created by ChenJie on 2/20/20.
//  Copyright © 2020 OrgName. All rights reserved.
//

#import "WeiboService.h"
#import <AFNetworking/AFNetworking.h>

@interface WeiboService ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation WeiboService
    
#pragma mark - Lifecycle methods

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

#pragma mark - Public methods

- (void)publicTimelineWithPageSize:(NSInteger)pageSize
                         pageIndex:(NSInteger)pageIndex
                           success:(void (^)(NSArray *messageList))success
                           failure:(void (^)(NSError *error))failure {
    
//    NSString *urlString = @"https://api.weibo.com/2/statuses/public_timeline.json";
    
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    NSString *accessToken = kAccessToken;
    accessToken = pageIndex > 6 ? @"sdfs" : kAccessToken;
    
    NSDictionary *parameters = @{
        @"access_token": accessToken,
        @"count": @(pageSize),
        @"page": @(pageIndex),
    };
    
    [self.manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"progress: %ld/%ld", (long)downloadProgress.completedUnitCount, (long)downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"success with response: %@", responseObject);
        
        NSArray *messageList = @[];
        if ([responseObject isKindOfClass:NSDictionary.class]) {
            messageList = responseObject[@"statuses"];
        }
        
        !success ?: success(messageList);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"fail with error: %@", error);
        
        !failure ?: failure(error);
    }];
}

#pragma mark - Private methods



#pragma mark - Delegate methods



#pragma mark - Setter



#pragma mark - Getter

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _manager = manager;
    }
    return _manager;
}

#pragma mark - Memory management methods

- (void)dealloc {
}

@end
